package com.ebt.m.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.conn.util.InetAddressUtils;

import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

public class EbtUtils {
    /**
     * 没有网络
     */
    public static final int APN_TYPE_NONE = -1;
    /**
     * Mobile data connection
     */
    public static final int APN_TYPE_MOBILE = 0;
    /**
     * WIFI data connection
     */
    public static final int APN_TYPE_WIFI = 1;

    public EbtUtils() {

    }

    /**
     * 检测sd卡是否存在
     *
     * @return
     */
    public static boolean checkSdCard() {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前的网络状态
     *
     * @param context
     * @return -1:没有网络 1:wifi 2:wap 3: net网络
     */
    public static int getAPNType(Context context) {
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected()) {
            return APN_TYPE_NONE;
        }
        switch (networkInfo.getType()) {
            case ConnectivityManager.TYPE_MOBILE:
                return APN_TYPE_MOBILE;
            case ConnectivityManager.TYPE_WIFI:
                return APN_TYPE_WIFI;
            default:
                return APN_TYPE_NONE;
        }
    }

    /**
     * 网络可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkEnabled(Context context) {
        return APN_TYPE_NONE != getAPNType(context);
    }

    /**
     * 短Toast
     *
     * @param context
     * @param text
     */
    public static void smallToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 短Toast
     *
     * @param context
     * @param resId
     */
    public static void smallToast(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    /**
     * 短Toast
     *
     * @param context
     * @param text
     */
    public static void smallCenterToast(Context context, String text) {
        Toast to = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        to.setGravity(Gravity.CENTER, 0, 0);
        to.show();
    }

    /**
     * 长Toast
     *
     * @param context
     * @param text
     */
    public static void bigToast(Context context, String text) {
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }

    /**
     * 根据类名获得tag
     */
    public static String getTag(Class clazz) {
        if (null != clazz) {
            return clazz.getName();
        }
        return "";
    }

    /**
     * 设置tab的默认样式，设置之后文字居中对齐，tab高度自适应
     *
     * @param mTabHost
     * @param tabHeight
     */
    public static void setCurrTabStyle(TabHost mTabHost, int tabHeight) {
        // 修改tab的默认样式
        TabWidget tabWidget = mTabHost.getTabWidget();

        for (int i = 0; i < tabWidget.getChildCount(); i++) {
            View child = tabWidget.getChildAt(i);
            final TextView tv = (TextView) child.findViewById(android.R.id.title);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tv.getLayoutParams();
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0); // 取消文字底边对齐
            params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); // 设置文字居中对齐
            child.getLayoutParams().height = tabHeight;

            // if (mTabHost.getCurrentTab() == i) {
            // tv.setBackgroundColor(color.desktop_curr_tab);
            // } else {
            // tv.setBackgroundColor(color.red);
            // }
        }
    }

    /**
     * 获取DisplayMetrics对象
     *
     * @param context
     * @return
     */
    public static DisplayMetrics getDisplay(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();
        return dm;
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = getDisplay(context);
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = getDisplay(context);
        return dm.heightPixels;
    }

    /**
     * 检测数据库文件所在目录是否存在
     *
     * @return
     */
    public static boolean checkDb() {
        String dbPath = ConfigData.DATABASE_PATH;
        String dbFile = ConfigData.DATABASE;
        File file1 = new File(dbPath);
        File file2 = new File(dbFile);
        if (!file1.exists() || !file1.canRead()) {
            file1.mkdirs();// 不存在就创建目录
            return false;
        }
        if (!file2.exists() || !file2.canRead() || !file2.isFile()) {
            return false;
        }
        return true;
    }

    /**
     * 检测helper数据库文件所在目录是否存在
     *
     * @return
     */
    public static boolean checkhelperDb() {
        String dbPath = ConfigData.HELPERDATABASE_PATH;
        String dbFile = ConfigData.HELPERDATABASE;
        File file1 = new File(dbPath);
        File file2 = new File(dbFile);
        if (!file1.exists() || !file1.canRead()) {
            file1.mkdirs();// 不存在就创建目录
            return false;
        }
        if (!file2.exists() || !file2.canRead() || !file2.isFile()) {
            return false;
        }
        return true;
    }

    /**
     * 判断资源库路径是否存在
     *
     * @return
     */
    public static boolean checkRepository() {
        String repositoryPath = getCompleteRepositoryPath();
        File file1 = new File(repositoryPath);
        if (!file1.exists()) {
            file1.mkdirs();
            return false;
        }
        return true;
    }

    /**
     * 返回Long
     *
     * @param resource
     * @return
     */
    public static Long formatLongFromString(String resource) {
        if (resource == null) {
            return null;
        }
        if (resource.matches("\\d+")) {
            return Long.valueOf(resource);
        }
        return null;
    }

    /**
     * 返回Integer
     *
     * @param resource
     * @return
     */
    public static Integer formatIntegerFromString(String resource) {
        if (resource == null) {
            return null;
        }
        if (resource.matches("\\d+")) {
            return Integer.valueOf(resource);
        }
        return null;
    }

    /**
     * 根据类型获得头像文件的文件名格式
     *
     * @param type
     */
    public static String getPortraitFileName(int type) {
        Date date = new Date(System.currentTimeMillis());// 当前系统时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.PRC);
        String result = null;
        switch (type) {
            case 0:
                result = sdf.format(date);
                break;
            case 1:
                result = "";
                break;
            default:
                result = "ebt";
                break;
        }
        return result;// 默认返回以系统日期为格式的文件名
    }

    /**
     * 获得后缀名
     *
     * @param code
     * @return
     */
    public static String getSuffix(int code) {
        String suffix = null;
        switch (code) {
            case 0:
                suffix = ".png";
                break;
            case 1:
                suffix = ".jpg";
                break;
            default:
                suffix = ".ebt";
                break;
        }
        return suffix;
    }

    /*
     * 获得头像文件的全路径-包含文件名称和后缀
     */
    public static String getCompletePortraitPath() {
        return ConfigData.PORTRAITPATH + File.separator + getPortraitFileName(0) + getSuffix(0);
    }

    /**
     * 获得完整的资源库文件全路径
     *
     * @return
     */
    public static String getCompleteRepositoryPath() {
        return ConfigData.REPOSITORY_PATH;
    }

    /**
     * 获得本机ip地址方式1
     *
     * @return
     */
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
//			Log.e("WifiPreference IpAddress", ex.toString());
        }
        return null;
    }

    /**
     * 获得本机Ip地址方式2
     *
     * @param useIpv4
     * @return
     */
    public static String getLoacalIpAddress(boolean useIpv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            List<InetAddress> addrs = null;
            for (NetworkInterface intf : interfaces) {
                addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    // 回环地址127.8.
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIpv4 = InetAddressUtils.isIPv4Address(sAddr);
                        if (useIpv4) {
                            if (isIpv4) {
                                return sAddr;
                            }
                        } else {
                            if (!isIpv4) {
                                int delim = sAddr.indexOf("%");// ipv6端口前面的前缀
                                return delim < 0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return "";
    }

    /**
     * 获得本机网卡地址
     *
     * @return
     */
    public String getLocalMacAddress(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /**
     * 获得当前目录下的可用空间
     *
     * @param path 目标目录
     * @return
     */
    public static long getUsableSpace(File path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return path.getUsableSpace();
        }
        final StatFs stats = new StatFs(path.getPath());
        return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
    }

    /**
     * 判断是否外置存储存在
     *
     * @return
     */
    public static boolean isExternalStorageRemovable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return Environment.isExternalStorageRemovable();
        }
        return true;
    }

    /**
     * 判断是否具有缓存目录
     *
     * @return
     */
    public static boolean hasExternalCacheDir() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    public static File getExternalCacheDir(Context context) {
        if (hasExternalCacheDir()) {
            return context.getExternalCacheDir();
        }
        // Before Froyo we need to construct the external cache dir ourselves
        final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
        return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
    }

    /**
     * 获得bitmap的大小
     *
     * @param bitmap
     * @return bitmap大小
     */
    @SuppressLint("NewApi")
    public static int getBitmapSize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            return bitmap.getByteCount();
        }
        // Pre HC-MR1
        return bitmap.getRowBytes() * bitmap.getHeight();
    }

    /**
     * 动态调整listview高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }


    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    /**
     * 检查 URI字符串中是否包含http：// 如果没有则 添加
     */
    public static String CheckURL(String url) {
        final String http = "http://";
        String uri = url;

        if (url != null && !url.isEmpty()) {
            if (url.startsWith(http)) {
                return url;
            } else {

                return http + url;
            }
        } else {
            return "";
        }
    }

    /**
     * 职业类别大写 "一", "二", "三", "四", "五", "六"
     *
     * @return
     */
    public static String getCareerCategoryCn(int careerCategory) {
        if (careerCategory == 0 || careerCategory > 6)
            return "数据异常";
        String[] num = new String[]{"零", "一", "二", "三", "四", "五", "六"};

        return num[careerCategory];
    }
}
